from pydantic import BaseModel, Field
from typing import Optional,Any,Union
from fastapi import Header, HTTPException, Depends
from fastapi.security import APIKeyHeader
import time
import hashlib
import importlib.util
import os, sys,subprocess
try:
    import tool.public_tool
except:
    import public_tool
from tool.logging_tool import info_print,error_print
API_KEY_HEADER = "X-API-KEY"
EXPECTED_API_KEY = "xeval_v1.0"  # 替换为你的实际API密钥

def check_auth(req_key="",key: str=EXPECTED_API_KEY) -> bool:
    key,key_str = auth_key(key)
    info_print("auth check:",req_key,key_str,key)
    if req_key!=key:
        return False
    return True
    pass
def auth_key(key: str=EXPECTED_API_KEY) -> bool:
    """
    验证API密钥
    :param key: API密钥
    :return: 是否验证通过
    """
    date=time.strftime("%Y-%m-%d", time.localtime())
    key_str=f"{key}_{date}".strip()
    # md5
    m = hashlib.md5()
    m.update(key_str.encode('utf-8'))
    key = m.hexdigest()
    return key,key_str
async def verify_api_key(x_api_key: str = Header(None, alias=API_KEY_HEADER)):
    """
    验证 X-API-KEY 是否有效
    """
    if x_api_key is None:
        raise HTTPException(status_code=401, detail=f"Missing {API_KEY_HEADER} header")
    # 你可以将 auth_key 逻辑放在这里，或者调用它
    # 为了简单起见，这里直接比较
    if check_auth(x_api_key) is False:
        raise HTTPException(status_code=401, detail="Invalid API Key")
    return x_api_key # 或者返回 True，或者解析后的用户信息等
class APIRes(BaseModel):
    # 模型名称 or 模型路径 自定义模型
    status_code:Optional[int]=Field(default=200,description="200成功, 401未授权, 404未找到, 500服务器错误等")
    data:Optional[Any|None]=Field(default=None,description="额外数据返回，可选")
    detail:Optional[str]=Field(default='',description="消息")
# info_print("API工具加载完成")
# info_print("API_KEY:",auth_key())

def pip_check(package):
    """
    检查指定的Python包是否已安装
    :param package: 包名
    :return: bool, 是否已安装
    """
    print(f"检查模块 {package} 是否已安装...")
    return importlib.util.find_spec(package) is not None

def pip_install(package,version=None):
    """
    检查并自动安装指定模块
    :param package: 包名
    """
    try:
        if importlib.util.find_spec(package) is None:
            print(f"{package} 未安装，正在自动安装...")
            if version is not None:
                package = f"{package}=={version}"
            subprocess.check_call([sys.executable, "-m", "pip", "install", package])
        else:
            print(f"{package} 已安装")
        return True
    except Exception as e:
        print(f"安装 {package} 时出错: {e}")
        return False
def pip_import(package):
    """
    检查并自动安装指定模块，并返回模块对象
    :param package: 包名
    :return: 模块对象
    """
    try:
        pip_install(package)
        return importlib.import_module(package)
    except Exception as e:
        print(f"安装或导入 {package} 时出错: {e}")
    raise ImportError(f"无法导入模块 {package}")
# 示例用法
# ensure_module("requests")
def install_modules(module_require_list=[]):
    """安装模块
    module_require_list=[["timm","0.9.10"],["munch","4.0.0"]]
    Args:
        module_require_list (list, optional): _description_. Defaults to [].
    """
    for module in module_require_list:
        try:
            if not pip_check(module[0]):
                info_print(f"模块 {module} 未安装，正在安装...")
                pip_install(*module)
            else:
                info_print(f"模块 {module} 已安装")
        except Exception as e:
            error_print(f"安装模块 {module} 时出错: {e}")
if __name__=="__main__":
    print(auth_key())
    timm=pip_import("timm")